package org.itboys.mobile.service.mongo.mobile;


import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.formula.functions.T;
import org.itboys.admin.entity.lasted.SystemDictionary;
import org.itboys.admin.service.lasted.SystemDictionaryService;
import org.itboys.commons.ErrorException;
import org.itboys.commons.utils.tools.ListUtil;
import org.itboys.commons.utils.tools.LongUtil;
import org.itboys.framework.resource.ResourceHolder;
import org.itboys.mobile.common.SundayCommonConstants;
import org.itboys.mobile.entity.mongo.TianJieMember;
import org.itboys.mobile.entity.mysql.TianJieGroup;
import org.itboys.mobile.entity.mysql.TianJieWallet;
import org.itboys.mobile.service.mysql.mobile.TianJieMobileGroupService;
import org.itboys.mobile.service.mysql.mobile.TianJieMobileWalletService;
import org.itboys.mobile.util.Md5UtilJx;
import org.itboys.mobile.util.NickNameUtil;
import org.itboys.mongodb.core.MongoDataSource;
import org.itboys.mongodb.service.BaseMongoService;
import org.itboys.param.PageResult;
import org.itboys.param.ParamUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 作者：jiangxiong
 * 日期：2017年5月8日
 * 联系方式 ：empty90911@126.com
 * 描述：天街_金融_用户_service
 */
@Service
public class TianJieMobileMemberService extends BaseMongoService<TianJieMember> {
    @Autowired
    private TianJieMobileGroupService groupService;
    @Autowired
    private ResourceHolder resourceHolder;
    @Autowired
    private SundayMobileCodeService codeService;
    @Autowired
    private TianJieMobileCollectionService collectionService;
    @Autowired
    private TianJieMobileWalletService walletService;

    @Autowired
    private SystemDictionaryService dictionaryService;






    @Resource(name = "mobileDs")
    private MongoDataSource mobileDataSource;
    @Override
    protected MongoDataSource getMongoDataSource() {
        return mobileDataSource;
    }

    @Override
    protected Class<TianJieMember> getEntityClass() {
        return TianJieMember.class;
    }


    /**
     * 校验当前用户是否是团队管理员。打开个人中心时校验
     * -------------重要。此接口作为金融模块入库，可以示例化金融模块用户的一些基本信息
     * @param memberId
     * @return
     */
    public Integer checkIsCaptain(Long memberId){
        TianJieMember member =super.getById(memberId);
        //实例化金融用户信息
        if(member.getFinanceIsFinance()==null||member.getFinanceIsFinance()==0){
            member.setFinanceIsCaptain(SundayCommonConstants.NO);
            member.setFinanceIsFinance(SundayCommonConstants.YES);
            member.setFinanceGroupId(0l);
            member.setFinanceTjId(0l);
            member.setFinanceTjPath(String.valueOf(memberId));
           // member.setFinanceStatus(SundayCommonConstants.YES);
            super.updateExceptEmpty(memberId,member);
        }
        if(member.getFinanceIsCaptain()!=null&&member.getFinanceIsCaptain()==1){
            return 1;
        }else{
            return 0;
        }

    }
    /**
     *
     */
    /**
     *  * 校验当前用户是否是团队管理员。打开个人中心时校验
     * -------------重要。此接口作为金融模块入库，可以示例化金融模块用户的一些基本信息
     * @param memberId
     * @return
     */
    public Map<String,Object> checkIsCaptain2(Long memberId){
        Map<String,Object> result = new HashMap<String,Object>();
        int isCaptain=0;//是否是队长
       // String bitConAddress = "";//小比特币地址

        SystemDictionary blockSaleDay=dictionaryService.getDictionaryByKey2("blockSaleDay");
        String blockSaleInfo="1，区块链不允许提前卖出；/n" +
                "2，系统按照实际买入时间，"+blockSaleDay.getValue()+"天后自动卖出；/n" +
                "3，持有币数将自动转入您的小比特币地址中，请提前注册小比特币地址。";//区块链自动卖出时间说明
        //String releaseInfo="";//待释放
        TianJieMember member =super.getById(memberId);
        //实例化金融用户信息
        if(member.getFinanceIsFinance()==null||member.getFinanceIsFinance()==0){
            member.setFinanceIsCaptain(SundayCommonConstants.NO);
            member.setFinanceIsFinance(SundayCommonConstants.YES);
            member.setFinanceGroupId(0l);
            member.setFinanceTjId(0l);
            member.setFinanceTjPath(String.valueOf(memberId));
            // member.setFinanceStatus(SundayCommonConstants.YES);
            super.updateExceptEmpty(memberId,member);
        }
        if(member.getFinanceIsCaptain()!=null&&member.getFinanceIsCaptain()==1){
            isCaptain=1;
        }
        result.put("isCaptain",isCaptain);
        result.put("bitConAddress",member.getFinanceBitAddress());
        result.put("blockSaleInfo",blockSaleInfo);
        result.put("info","字段说明：isCaptain：是否队长（1是0否）；bitConAddress：用户小比特币地址（提币账号）,blockSaleInfo：区块链卖出说明（内含转行符号）直接显示");

        return result;
    }

    /**
     * 更新用户比特币地址
     * @param memberId
     * @param bitAddress
     */
    public void updateBitAddress(long memberId,String bitAddress){
        TianJieMember member  = new TianJieMember();
        member.setId(memberId);
        member.setFinanceBitAddress(bitAddress);
        super.updateExceptEmpty(memberId,member);
    }
    /**
     * 获取团队中信息：团队名称、团队队长、团队组员
     * @param memberId
     */
    public Map<String,Object> getGroupInfo(Long memberId){
        Map<String,Object> result = new HashMap<>();
        TianJieMember member=super.getById(memberId);
        TianJieGroup group=groupService.find(member.getFinanceGroupId());

        Map<String,Object> param = new HashMap<>();
        param.put("financeGroupId",member.getFinanceGroupId());
        List<TianJieMember> members=super.list(param);
        List<Map<String,Object>> partners=new ArrayList<>();
        String imgRoot =resourceHolder.getStringValue("imgRoot");
        for(TianJieMember m:members){
            Map<String,Object> partner = new HashMap<>();
            partner.put("id",m.getId());
            partner.put("userName", m.getUserName());
            partner.put("nickName",m.getNickName());
            partner.put("logo",imgRoot+m.getLogo());
            partner.put("createTime",m.getCreateTime());
            if(m.getFinanceIsCaptain()==1){
                partner.put("isCaptain",1);
                partner.put("isCaptainInfo","队长开启拨付按钮");
            }else{
                partner.put("isCaptain",0);
                partner.put("isCaptainInfo","队员开启拨付按钮");
            }
            partners.add(partner);
        }

        result.put("groupName",group.getName());
        result.put("groupCaptain",group.getCaptainName());
        result.put("partnerSize",partners.size());
        result.put("partners",partners);

        return result;
    }

    /**
     * 推荐注册
     * @param tjMemberId 推荐人ID
     * @param validateCode
     * @param password
     */
    public void share_reg(Long tjMemberId,String validateCode,String mobile,String password){
        int check_code=codeService.checkCode(mobile,validateCode, SundayCommonConstants.validate_code_type_register);
        if(check_code!=0){
          throw new ErrorException("验证码错误。");
        }
        Map<String,Object> param = new HashMap<>();
        param.put("userName",mobile);
        long count =super.count(param);
        if(count>0){
            throw new ErrorException("该手机号已被注册。");
        }
        TianJieMember tjMember = super.getById(tjMemberId);
        TianJieMember member = new TianJieMember();
        //商城基本属性
        member.setNickName(NickNameUtil.getRandomNickName());
        member.setLogo(NickNameUtil.getRandomLogo());
        member.setUserName(mobile);
        member.setPassword(Md5UtilJx.GetMD5Code(password));
        member.setUserType(1);
        //member.setCreator(creator);
        member.setZoneId(1l);
        member.setIsDeleted(2);
        member.setIsWeiboLogin(2);
        member.setIsWeixinLogin(2);
        member.setIsQqLogin(2);

        //金融基本属性
        member.setFinanceGroupId(tjMember.getFinanceGroupId());
        member.setFinanceGroupName(tjMember.getFinanceGroupName());
        member.setFinanceIsFinance(SundayCommonConstants.YES);
        member.setFinanceIsCaptain(SundayCommonConstants.NO);
        //金融-自己的推荐属性
        member.setFinanceTjId(tjMemberId);
      //  member.setFinanceStatus(SundayCommonConstants.YES);
        super.save(member);
        //修改自己的推荐链
        logger.info("被推荐人的ID="+member.getId());
        String tjPath = StringUtils.isNotEmpty(tjMember.getFinanceTjPath())?tjMember.getFinanceTjPath()+"/"+member.getId():String.valueOf(member.getId());
        member.setFinanceTjPath(tjPath);
        super.updateExceptEmpty(member.getId(),member);
        //创建钱包
        walletService.getWallet(member.getId(),false);
        //将用户的小区加入到收藏表中。默认家境天成
        collectionService.addCollection(member.getId(), 1l, 3);
        //更新推荐人的属性(推荐人开区，即推荐人推荐的第一级队员)

        String firstPath=StringUtils.isNotEmpty(tjMember.getFinanceTjFirstPath())?
                tjMember.getFinanceTjFirstPath()+"/"+member.getId():
                String.valueOf(member.getId());
        logger.info("推荐人的第一级："+firstPath);
        tjMember.setFinanceTjFirstPath(firstPath);

        super.updateExceptEmpty(tjMemberId,tjMember);
        /*//2017年11月27日，将第一梯队推荐人写入到，自己的钱包终
        walletService.findByMemberId()*/
    }

    /**
     * 获取我推荐的第一级会员即业绩
     * @param request
     * @param memberId
     * @return
     */
    public List<Map<String,Object>> getAchievement(HttpServletRequest request,Long memberId){
        List<Map<String,Object>> results = new ArrayList<>();
        Map<String,Object> param =new HashMap<String,Object>();
        param.put("financeTjId",memberId);
        Map<String,String>  containsparam=ParamUtil.packageMongoVagueParam(request,"nickName");
        PageResult<TianJieMember> pageResult =super.containpageQuery(request,containsparam,param);

        List<Long> memberIds = new ArrayList<Long>();
        for(TianJieMember member:pageResult.getData()){
            memberIds.add(member.getId());
        }
        param.clear();
        //匹配业绩
        if(ListUtil.isNull(memberIds))return results;
        param.put("memberIds",memberIds);
        List<TianJieWallet> wallets=walletService.select(param);
        for(TianJieMember member:pageResult.getData()){
            Map<String,Object> result =new HashMap<String,Object>();
            result.put("id",member.getId());
            result.put("nickName",member.getNickName());
            result.put("userName",member.getUserName());
            result.put("createTime",member.getCreateTime());
            result.put("createDate",member.getCreateDate());
            result.put("totalAchievement",0.00);
            for(TianJieWallet wallet:wallets){
                if(LongUtil.isNotZreo(wallet.getMemberId())&&
                        member.getId()==wallet.getMemberId().longValue()){
                    result.put("totalAchievement",wallet.getTotalAchievement());
                break;
                }
            }
            results.add(result);
        }
        return results;
    }



}
